var arrEvent;
$(function() {
    $('#calendar').fullCalendar({
        header: {left: 'agendaDay,agendaWeek', center: 'prev title next', right: 'today'},
        views: {agendaDay: {groupByResource: true}},
        droppable: true,
        defaultView: 'agendaDay',
        allDaySlot: false,
        navLinks: true,
        selectable: true,
        selectHelper: true,
        editable: true,
        eventLimit: true,
        lazyFetching: true,
        handleWindowResize: true,
        nowIndicator: true,
        titleFormat: 'dddd YYYY-MM-DD',
        minTime: "07:00:00",
        maxTime: "20:00:00",
        height: window.innerHeight - 30,
        slotDuration: "00:15:00",
        slotLabelFormat: 'HH',
        slotLabelInterval: "00:60:00",
        slotLabelFormats: 'mm',
        slotLabelIntervals: "00:15:00",
        selectMinDistance: 30,
        timeFormat: 'H:mm',
        slotEventOverlap: false,
        schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
        dragRevertDuration: 200,
        unselectAuto: false,
        groupByResource: false,
        backgroundColor: "#FFFFFF",
        groupByDateAndResource: false,
        refetchResourcesOnNavigate: true,
        windowResize: function(view) {
            $('#calendar').fullCalendar('option', 'height', window.innerHeight - 52)
        },
        select: function(startDate, endDate, jsEvent, view, resource) {   //市场创建预约
            let continued = moment(endDate).diff(moment(startDate), 'minutes'); // 时间差
            if(view.type === 'agendaDay'){  // 判断是否在医生视图
                let eventData = moment(startDate).format('YYYY-MM-DD HH:mm:ss') + "," +  // 起始时间
                    moment(endDate).format('YYYY-MM-DD HH:mm:ss') + "," +    // 结束时间
                    resource.id + "," +  // 获取的医生
                    continued;    // 数字化时间差
                let index = layer.open({
                    type: 2,
                    title: '添加预约客户',
                    area: ['70%', '95%'],
                    fix: true,
                    maxmin: true,
                    content: Feng.ctxPath + '/reservationTcView/doctor_addTaskTcMarket/' + eventData
                });
                this.layerIndex = index
            }
            $('#calendar').fullCalendar('unselect')
        },
        resources: function(callback, start, end, timezone) {
            let endTime = moment(end).subtract(1, 'seconds').format('YYYY-MM-DD HH:mm:ss');
            let timeSlot = moment(start).format('YYYY-MM-DD HH:mm:ss') + "," + endTime;
            //  请求TC数据
            $.post(Feng.ctxPath + '/reservationTcView/getRMTcViewListed/' + timeSlot, function (data) {
                let doctorList = [];
                $.each(data, function (key, value) {
                    let arr = {
                        id: value.id,
                        title: value.tcName
                    };
                    doctorList.push(arr)
                })
                callback(doctorList)
            },'json')
        },
        events: function(start, end, timezone, callback) {
            let endTime = moment(end).subtract(1, 'seconds').format('YYYY-MM-DD HH:mm:ss');
            let timeSlot = moment(start).format('YYYY-MM-DD HH:mm:ss') + "," + endTime;
            //  请求当天数据
            $.post(Feng.ctxPath + '/reservationTcView/getDataTcList/' + timeSlot, function (data) {
                let events = [];
                $.each(data, function (key, value) {
                    let obj = {
                        id: value.customerId,
                        title: value.appointmentPayService,
                        start: new Date(Date.parse(value.startTime)),
                        end: new Date(Date.parse(value.endTime)),
                        customerName: value.customerName,
                        resourceId: value.id,
                        medicalRecordNumber: value.medicalRecordNumber,
                        customerPhone: value.customerPhone,
                        customerAge: value.customerAge,
                        doctor: value.doctor,
                        arrivalStore: value.arrivalStore,
                        fieldTc: value.fieldTc,
                        remarksReservation: value.remarksReservation,
                        firstVisitDate: value.firstVisitDate,
                        filingTime: value.filingTime,
                        archiving: value.archiving,
                        birthday: value.birthday,
                        createAppointmentTime: value.createAppointmentTime,
                        arrivalStatus: value.arrivalStatus,
                        customerStatus: value.customerStatus,
                        reservationsId: value.reservationsId,
                        accountarrears: value.accountarrears,
                        todaySum: value.todaySum,
                        aftersSum: value.aftersSum,
                        beforeSum: value.beforeSum,
                        yellowNumber: value.yellowNumber,
                        sex: value.sex,
                        remarks: value.remarks,
                        checkStatus: value.checkStatus,
                        customerSexHead:value.customerSexHead
                    };
                    obj.borderColor = "#FFFFFF";
                    obj.backgroundColor = value.arrivalStatus === '1' ? "#4BBCFF" :
                        value.arrivalStatus === '2' ? "#10428b" :
                            value.arrivalStatus === '3' ? "#ffba40" :
                                value.arrivalStatus === '4' ? "#2dc87e" :
                                    value.arrivalStatus === '5' ? "#61b740" :
                                        value.arrivalStatus === '6' ? "#017cdc" :
                                            value.arrivalStatus === '9' ? "#4bbcff" :
                                                value.arrivalStatus === '10' ? "#017cdc" :
                                                    value.arrivalStatus === '13' ? "#FDAEBE" :
                                                        value.arrivalStatus === '14' ? "#FDAEBE" :  "gray"
                    events.push(obj);
                });
                callback(events);
            },'json')
        },
        eventClick: function(calEvent, jsEvent, view) {
            arrEvent = calEvent ;
            $('a').removeClass('shadow');
            $(this).addClass('shadow').css("border-color", "white ").attr('id', calEvent.id);
            jsEvent.stopPropagation();

            let patientContent = '';    //内容
            let patientTotalBtn = '';   // 按钮总容器

            patientContent = '<div style="color: #555555;">' +
                '<div style="display: flex;padding: 5px 0;">' +
                '<div><img src="'+calEvent.customerSexHead +'" alt="..." width="60px;"></div>' +    //  头像
                '<div style="flex: 1;margin-left: 10px;">' +
                '<div>' +
                '<span style="color: #319dbc;font-size: 16px;font-weight: bold;cursor:pointer;" onclick="openBilee(' + "'" + calEvent.id + "'" + ')">' + calEvent.customerName + '</span>' +
                '<span style="margin: 0 11px;">' + calEvent.arrivalStore + '</span>' +
                '<span>' + calEvent.customerStatus + '</span>' +
                '</div>' +
                '<div>' + calEvent.medicalRecordNumber + ' (' + calEvent.doctor + ')</div>' +
                '<div>' + calEvent.birthday + ' (' + calEvent.customerAge + '岁)</div>' +
                '<div style="font-size: 14px;font-weight: bolder"><span>' + calEvent.customerPhone + '</span></div>' +
                '</div>' +
                '</div>' +
                '<div class="patientTipsContent" style="border-top: 1px solid #cccccc;padding: 5px 0;">' +
                '<div><span class="patientTipsTitle">预约时间</span><span class="patientTipsSpan" style="font-weight: bold;font-size: 16px;">'+calEvent.start.format('HH:mm') + '-' + calEvent.end.format('HH:mm')+'</span></div>' +

                '<div><span class="patientTipsTitle">预约医生</span><span class="patientTipsSpan">'+calEvent.doctor+'</span></div>' +
                '<div><span class="patientTipsTitle">看诊项目</span><span class="patientTipsSpan">'+calEvent.title+'</span><a href="javascript:;" onclick="updAppointmentPayService(' + "'" + calEvent.id + "'" + ')">修改</a></div>' +
                '<div><span class="patientTipsTitle">预约备注</span><span class="patientTipsSpan overflow" title="' + calEvent.remarksReservation + '">'+calEvent.remarksReservation+'</span><a href="javascript:;" onclick="updRemarksReservation(' + "'" + calEvent.id + "'" + ')">修改</a></div>' +
                '<div><span class="patientTipsTitle">初诊日期</span><span class="patientTipsSpan">'+calEvent.firstVisitDate+'</span></div>' +
                '<div><span class="patientTipsTitle">创建时间</span><span class="patientTipsSpan">'+calEvent.createAppointmentTime+'</span></div>' +
                '<div><span class="patientTipsTitle">创建人</span><span class="patientTipsSpan">'+calEvent.archiving+'</span><a href="javascript:;" onclick="getUpdateLog(' + "'" + calEvent.id + "'" + ')">改动日志</a></div>' +
                '<div><span class="patientTipsTitle">黄页编号</span><span class="patientTipsSpan">'+calEvent.yellowNumber+'</span> </div>' +
                '</div>' +
                '</div>';

            if(calEvent.arrivalStatus === '1' || calEvent.arrivalStatus === '9' ){
                patientTotalBtn = '<div class="btnBox">' +
                    '<button type="button" class="btn" onclick="sureAppointmentSC(' + "'" + calEvent.id + "','" + calEvent.customerName + "'" + ',arrEvent)">确定</button> ' +
                    // '<button type="button" class="btn" onclick="cancelAppointment(' + "'" + calEvent.id + "'" + ')">取消</button> ' +
                    '<button type="button" class="btn" onclick="shortMessage(' + "'" + calEvent.id + "'" + ')">短信</button> ' +
                    '</div>';
            }
            test = layer.open({
                type: 4,
                tips: [2, '#ffffff'],
                closeBtn: 0,
                area: ['305px', 'auto'],
                content: ['<div>' + patientContent + '' + patientTotalBtn + '</div>', '#' + calEvent.id + ''],
                success: function (layero, index) {
                    if (($(layero).offset().top + $(layero).height()) > $(window).height()) {
                        $(layero).css("top", ($(window).height() - ($(layero).height() + 10)))
                    }
                }
            })
        },
        eventRender: function(calEvent, element, view) {
            if (calEvent.customerName === "" || calEvent.customerName == null) {
                element.prepend("<div class='myfc-title'><span>新建预约</span></div>")
            }
        },
        eventAfterRender: function (calEvent, element, view) {
            if (element[0].clientWidth < 24) {
                element[0].innerHTML = ""
            } else if (element[0].clientWidth >= 24 && element[0].clientWidth < 45) {
                element[0].innerHTML = "";
                element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div>")
            } else {
                if (calEvent.checkStatus === 1) {
                    if (calEvent.accountarrears !== 0) {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarksReservation + "</div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div><div style='position: absolute;right: 2px;top: 20px;color: white;background: #FF7E00;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em;z-index: 9;'>查</div>")
                    } else {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarksReservation + "</div><div style='position: absolute;right: 2px;top: 1px;color: white;background: #FF7E00;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>查</div>")
                    }
                } else {
                    if (calEvent.accountarrears !== 0) {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarksReservation + "</div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div>")
                    } else {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarksReservation + "</div>")
                    }
                }
            }
        },
        eventDrop: function (event, delta, revertFunc, jsEvent, ui, view) {
            if (event.arrivalStatus === '2' ||event.arrivalStatus === '3' ||event.arrivalStatus === '4' ||event.arrivalStatus === '5' || event.arrivalStatus === '7'
                ||event.arrivalStatus === '13' ||event.arrivalStatus === '14') {
                alert("此状态不能修改！");
                revertFunc()
            } else {
                if (confirm("您确定要修改预约么？")) {
                    let param = event.start.format('YYYY-MM-DD HH:mm:ss') + "," + event.end.format('YYYY-MM-DD HH:mm:ss') + "," + event.resourceId + "," + event.id;
                    $.post(Feng.ctxPath + '/reservationTcView/updateViewsTc/' + param, function (data) {
                        Feng.success('修改成功!')
                    },'json').fail(function(errorType){
                        revertFunc()
                    });
                } else {
                    revertFunc()
                }
            }
        },
        eventResize: function (event, delta, revertFunc, jsEvent, ui, view) {
            if (event.arrivalStatus === '2' ||event.arrivalStatus === '3' ||event.arrivalStatus === '4' ||event.arrivalStatus === '5' || event.arrivalStatus === '7'
                ||event.arrivalStatus === '13' ||event.arrivalStatus === '14') {
                alert("此状态不能修改！");
                revertFunc()
            } else {
                if (confirm("您确定要修改预约么？")) {
                    let param = event.start.format('YYYY-MM-DD HH:mm:ss') + "," + event.end.format('YYYY-MM-DD HH:mm:ss') + "," + event.resourceId + "," + event.id;
                    $.post(Feng.ctxPath + '/reservationTcView/updateViewsTc/' + param, function (data) {
                        Feng.success('修改成功!')
                    },'json').fail(function(xhr,errorText,errorType){
                        revertFunc()
                    });
                } else {
                    revertFunc()
                }
            }
        },
        loading: function(isLoading, view) {
            if (isLoading === true) {
                $(".fc-prev-button,.fc-next-button").css("pointer-events", "none")
            } else if (isLoading === false) {
                $(".fc-prev-button,.fc-next-button").css("pointer-events", "auto")
            }
        }
    });
    $("#calendar").on('click', 'h2', function() {
        laydate({
            istime: true,
            format: 'YYYY-MM-DD',
            choose: function(value) {
                $('#calendar').fullCalendar('gotoDate', value)
            }
        })
    })
});

function fullCalendarChange() {}